import { handlingTime } from "./tool"
export const mutations = {
    // 获取audio dom对象
    getAudio(state) {
        state.audio = document.getElementById("myaudio")
    },
    // 更改播放器的播放状态
    changeState(state) {
        state.audioState = !state.audioState
    },
    // 更改播放模式
    changeModel(state, index) {
        state.model = index
    },
    //点击歌曲时触发的事件
    upDateSong(state, data) {
        state.song = data.music
        let music = data.music

        // 判断播放列表中是否已经存在该歌曲
        var result = state.list.findIndex(item => {
            return music.id === item.id
        })
        //不存在则添加到播放列表中
        if (result == -1) {
            var newsong = {
                name: music.songName,
                author: music.author,
                id: music.id,
                picUrl: music.picUrl
            }
            state.list.push(newsong);
            state.index = state.list.length - 1;
        } else {  //存在则只修改index的值
            state.index = result
        }

        //获取到audio标签
        var audio = document.getElementById("myaudio");
        if (data.autoplay) {  //判断传递过来的autoplay的值，因为在打开网页时歌曲是不自动播放的
            audio.setAttribute("autoplay", "autoplay");
            state.audioState = true
        } else {
            state.audioState = false
        }
        //将歌曲列表存储到本地
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },
    // 更新播放状态，歌曲是否可以播放  歌曲名字由  正在加载中--->歌曲真正的名称
    upDateStatus(state, newName) {
        state.song.name = newName
    },
    // 删除歌曲列表中的歌曲
    delete(state, index) {
        state.list.splice(index, 1);
        if (state.list == 0) {  //歌曲列表为空
            state.index = 0;
        } else if (index == state.index) {  //删除的歌曲是正在播放的歌曲
            if (index == state.list.length - 1) {  //并且是最后一首歌曲
                state.index = 0;
            } else {
                state.index = index;
            }
            var item = state.list[state.index]
            this.dispatch("getSong", { id: item.id, autoplay: true })
        } else if (index < state.index) { //删除的正在播放歌曲前面的歌曲，需要修改index,否则会出现数组坍塌的情况
            state.index--
        }
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },

    // 清空列表
    deleteAll(state) {
        state.list = []
        state.index = 0
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },

    // 点击播放全部时触发的事件
    addlist(state, list) {
        state.index = state.list.length;
        // 遍历歌曲，查看歌单中的歌曲在歌曲列表中是否存在，如果存在则不添加，但是newlist数组中该项的值是undefined
        var newlist = list.map(item => {
            let res = state.list.findIndex(item2 => {
                return item.id == item2.id
            })
            if (res == -1) {
                return {
                    name: item.name,
                    author: item.ar[0].name,
                    id: item.id,
                    picUrl: item.al.picUrl
                }
            }
        })
        // 删除数组中的undefined项
        newlist = newlist.filter(Boolean)
        state.list.push(...newlist);
        var item = state.list[state.index]
        this.dispatch("getSong", { id: item.id, autoplay: true })
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },
    // 更新index
    upDateIndex(state, index) {
        if (state.index == index) return
        state.index = index
        var item = state.list[state.index]
        this.dispatch("getSong", { id: item.id, autoplay: true })
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },
    // 下一首
    next(state) {

        //判断播放模式（是循坏播放或者是单曲循环时，index++）
        if (state.model == 0 || state.model == 1) {
            if (state.index == state.list.length - 1) {
                state.index = 0
            } else {
                state.index++
            }
        } else {
            //是随机播放则产生一个随机数
            state.index = Math.ceil(Math.random() * state.list.length)
        }

        var item = state.list[state.index]
        this.dispatch("getSong", { id: item.id, autoplay: true })
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },
    //上一首
    prev(state) {
        if (state.model == 0 || state.model == 1) {
            if (state.index == 0) {
                state.index = state.list.length - 1
            } else {
                state.index--
            }
        } else {
            state.index = Math.ceil(Math.random() * state.list.length)
        }
        var item = state.list[state.index]
        this.dispatch("getSong", { id: item.id, autoplay: true })
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },
    // 初始化从本地读取缓存触发的事件
    pushlist(state, oldstate) {
        //当播放列表存在时才触发
        if (oldstate.list) {
            state.list = oldstate.list;
            state.index = oldstate.index;
            let item = state.list[state.index]
            this.dispatch("getSong", { id: item.id, autoplay: false })
        }
    },
    // 存入未读评论
    pushCom(state, arr) {
        state.unreadComments = arr
    },
    // 更新登陆状态
    changeIsLogin(state, boolean) {
        state.isLogin = boolean
    },
    // 更新admin的信息
    upDateAdmin(state, admin) {
        state.admin = admin
    },
    // 存储登陆用户的信息
    saveUser(state, user) {
        state.user = user
    },
    // 存储token
    saveToken(state, token) {
        state.token = token
    },
    // 播放暂停音乐
    play_pause(state) {
        if (state.audioState) {
            state.audio.pause()
            this.commit("changeState")
        } else {
            if (state.list.length == 0) {
                Vue.prototype.$EventBus.$emit("goMusic") //触发MiniPlay页面的事件
                Vue.prototype.$notify({
                    title: "警告",
                    message: "暂无播放列表,请在音乐库里选择要播放的音乐",
                    type: "warning",
                })
            } else {
                state.audio.play()
                this.commit("changeState")
            }
        }
    },
    // 更新音乐时长
    updateDuration(state, time) {
        state.duration = time
    },
    // 监听歌曲的进度，对应歌词
    listenLyrics(state) {
        state.lyricsIndex = 0
        state.audio.addEventListener("timeupdate", () => {
            state.currentTime = state.audio.currentTime
            let lyricArray = state.song.lyric
            if (lyricArray) {
                let length = lyricArray.length
                if (length) {
                    //遍历所有歌词
                    //最后一句歌词没有下一句,所以不需要跟下一句的时间做比较
                    if (state.lyricsIndex == length - 2) {
                        //判断当前的时间是否大于等于最后一句的时间
                        if (state.audio.currentTime >= lyricArray[length - 1][0]) {
                            //正在唱最后一句
                            state.lyricsIndex = length - 1
                        }
                    } else {
                        for (let i = 0; i < length - 1; i++) {
                            //将每个歌曲进度都跟数组中的歌词比较,在当前歌词的时间到下一句歌词的时间范围之内
                            let flag = state.audio.currentTime >= lyricArray[i][0] && state.audio.currentTime < lyricArray[i + 1][0]
                            if (flag) {
                                //设置正在播放的行号
                                state.lyricsIndex = i
                                break;
                            }
                        }
                    }
                }
            }
        })
    },
    // 设置音量
    setVolume(state, num) {
        state.audio.volume = num * 0.1
    },

    // 设置进度
    setProgress(state, num) {
        state.audio.currentTime = num
    },

    // 更改歌词的状态（显示和隐藏）
    changeShowLyrics(state) {
        state.showLyrics = !state.showLyrics
    },

    // 存储文章数据
    getArticle(state, array) {
        state.articleData = array
    },

    changeCanPlay(state, bool) {
        state.isCanPlay = bool
    },

    // 排行榜
    getRanking(state, playlist) {
        let splice1 = playlist.soaringList.slice(0, 8)
        let splice2 = playlist.newSongList.slice(0, 8)
        let splice3 = playlist.hotSongList.slice(0, 8)
        let splice4 = playlist.soaringList.slice(0, 8)
        state.spliceRanklingList = []
        state.spliceRanklingList.push(splice1, splice2, splice3, splice4)
        state.soaringList = playlist.soaringList
        state.newSongList = playlist.newSongList
        state.hotSongList = playlist.hotSongList
        state.theOriginalList = playlist.theOriginalList
        state.listOfSinger = playlist.listOfSinger
    },

    // 初始化socket
    initSocket(state, socket) {
        state.socket = socket
    },
    changeChatId(state, number) {
        state.chatId = number
    },
    // 更新群聊信息
    updateGroupChat(state, msg) {
        let list = []
        if (msg.length > 1) { // 从服务器获取的消息记录
            state.groupChat = []
            list.push(...handlingTime(msg, true))
        } else { // 新消息推送 
            if (state.groupChat.length > 1) {
                let last = state.groupChat[state.groupChat.length - 1]
                msg.unshift(last)
                let arr = handlingTime(msg, false)
                list.push(arr[1])
            }
        }
        state.groupChat.push(...list)
        list.push(...msg)

    },
    // 更新用户数组
    updateUsers(state, users) {
        state.onlineUsers = []
        state.onlineUsers.push(...users)
    },
    // 更新私聊信息
    updatePrivateChat(state, data) {
        if (!state.privateChat[data.account]) {
            state.privateChat[data.account] = []
        }
        state.privateChat[data.account].push(...data.msg_list)
    },
    // 是否禁言
    updateMute(state, bool) {
        state.mute = bool
    },

    // 更新路由
    updatePath(state, path) {
        state.path = path
    },

    // 更新同分类文章
    updateCategoryArticle(state, arr) {
        state.categoryArticle = []
        if (arr && arr.length > 0) {
            state.categoryArticle.push(...arr)
        }
    },
    // 更新评论通知
    updateNotify(state, obj) {
        state.notify = obj
    },
    // 更新留言通知
    updateInform(state, obj) {
        state.inform = obj
    },
    // 更新消息标识
    updatePrompt(state, data) {
        let { type, flag } = data
        if (type == "comment") {
            state.comPrompt = flag
            this.dispatch("ObtainNotice")
        } else {
            state.messPrompt = flag
            this.dispatch("ObtainInform")
        }
    }
}